import datetime
import decimal
import json


def toJson(data, indent=None):
    """
    数据转换为Json。
    :param data:
    :param indent:
    :return:
    """
    return json.dumps(data, cls=CustomJsonEncoder, ensure_ascii=False, indent=indent)


class CustomJsonEncoder(json.JSONEncoder):
    """
    Json解析器，解决识别Decimal出错的问题
    """

    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        if isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        if isinstance(obj, int):
            return int(obj)
        elif isinstance(obj, float):
            return float(obj)
        elif isinstance(obj, decimal.Decimal):
            return float(obj)
        # elif isinstance(obj, array):
        #    return obj.tolist()
        else:
            return super(CustomJsonEncoder, self).default(obj)